package cn.wangzg.netdemo;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.widget.ImageView;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

public class MainActivity extends AppCompatActivity {
    ImageView tupian;
    String path="https://n.sinaimg.cn/spider2021316/88/w1080h608/20210316/fa39-kmkptxc8344364.jpg";
    Handler handler=new Handler(){
        @Override
        public void handleMessage(@NonNull Message msg) {
            Bitmap bitmap= (Bitmap) msg.obj;
            tupian.setImageBitmap(bitmap);
        }
    };
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        tupian=findViewById(R.id.imageView);
        new Thread(){
            @Override
            public void run() {
                downPic(path);
            }
        }.start();

    }
    private void downPic(String strUrl){
        try {
            URL url=new URL(strUrl);
            HttpURLConnection conn= (HttpURLConnection) url.openConnection();
            if(conn.getResponseCode()==200){
                InputStream inputStream = conn.getInputStream();//ctrl+alt+v
                Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
                //tupian.setImageBitmap(bitmap);
                Message msg=new Message();
                msg.obj=bitmap;
                handler.sendMessage(msg);
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}